package com.yly.constant;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.yly.utils.StrUtil;

/**
 * 可用Properties文件配置的Constants基类.
 * 本类既保持了Constants的static和final(静态与不可修改)特性,又拥有了可用Properties文件配置的特征,
 * 主要是应用了Java语言中静态初始化代码的特性. <p/> 子类可如下编写
 * 
 * <pre>
 *   public class Constants extends ConfigurableConstants {
 *    static {
 *      init(&quot;ouy.properties&quot;);
 *   }
 *   &lt;p/&gt;
 *   public final static String ERROR_BUNDLE_KEY = getProperty(&quot;
 *   constant.error_bundle_key&quot;, &quot;errors&quot;); }
 * </pre>
 * 
 */
public class ConfigurableConstants {
	protected static Log loger = LogFactory.getLog(ConfigurableConstants.class);

	protected static Properties p = new Properties();
	

	protected static String propertyFileName = "constants.properties";
	/**
	 * 静态读入属性文件到Properties p变量中
	 */
	static {
		loger.debug("初始化配置文件" + propertyFileName + "到 Constants....");
		InputStream in = null;
		try {
			in = ConfigurableConstants.class.getClassLoader()
					.getResourceAsStream(propertyFileName);
			if (in != null) {
				p.load(in);
			}
		} catch (IOException e) {
			loger.error("初始化配置文件 " + propertyFileName
					+ " 到 Constants 发生错误,请检查相关配置文件!" + e);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					loger.error("close " + propertyFileName + " error!");
				}
			}
		}
	}

	/**
	 * 
	 * 封装了Properties类的getProperty函数,使p变量对子类透明.
	 * 
	 * @param key
	 *            property key.
	 * @param defaultValue
	 *            当使用property key在properties中取不到值时的默认值.
	 * @return 属性值
	 */
	public static String getProperty(String key, String defaultValue) {
		if (defaultValue != null) {
			return p.getProperty(key, defaultValue);
		}
		return p.getProperty(key);
	}

	/**
	 * 
	 * 封装了Properties类的getProperty函数,使p变量对子类透明.
	 * 
	 * @param key
	 *            property key.
	 * @return 属性值
	 */
	public static String getProperty(String key) {
		return getProperty(key, null);
	}

	
	public static String getPropertyAddValue(String key, String addValue) {
		String propertyValue = getProperty(key, null);
		
		if(!(StrUtil.nil(propertyValue)) && propertyValue.lastIndexOf(addValue) != propertyValue.length() - 1){
			propertyValue += addValue;
		}
		return propertyValue;
	}
}
